package cc.bookcloud.tool.ocr.service.impl;

import cc.bookcloud.tool.ocr.config.ExportConstants;
import cc.bookcloud.tool.ocr.domain.Tables;
import cc.bookcloud.tool.ocr.mapper.TableMapper;
import cc.bookcloud.tool.ocr.service.ITableService;
import cc.bookcloud.tool.ocr.util.ApiResult;
import cc.bookcloud.tool.ocr.util.DateTimeUtils;
import cc.bookcloud.tool.ocr.util.TableToWordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p> 实现类 </p>
 *
 * @author : zhaoqiuyue
 * @description :
 * @date : 2019/11/8 16:22
 */
@Slf4j
@Service
public class TableService implements ITableService {

    @Autowired
    private TableMapper tableMapper;
    @Autowired
    private TableToWordUtil tableToWordUtil;

    @Override
    public ApiResult getTableInfo(String dbName) {
        File file = new File("D:\\workBase\\test2.0\\release-assist-tool\\src\\main\\resources\\库表转word文本");
        ArrayList<String> list = fileToList(file);
        return getTables(list,dbName);
    }

    private ApiResult getTables(ArrayList<String> list, String dbName) {

        if(dbName==null){
            dbName= ExportConstants.DATABASE;
        }
        List<Tables> tables = null;
        // 1、获取数据库所有表信息(若param传入表名则导出单个表信息)
        tables = tableMapper.getAllTables(dbName, list);
        if (CollectionUtils.isEmpty(tables)) {
            return ApiResult.fail("数据库或表信息不存在");
        }
        // 2、生成文件名信息 - 年月日时分秒
        String date = null;
        try {
            date = DateTimeUtils.dateFormat(new Date(), DateTimeUtils.PARSE_PATTERNS[12]);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String docFileName = ExportConstants.FILE_PATH + "\\" + ExportConstants.FILE_NAME + "-" + date + ".doc";

        // 3、调用工具类生成文件
        tableToWordUtil.toWord(tables, dbName,docFileName, ExportConstants.FILE_NAME);

        // 4、返回文件地址
        String filePath = docFileName.replaceAll("\\\\", "/");
        return ApiResult.ok("导出数据库表信息生成Word成功", filePath);
    }

    //将文件内容转换为字符串列表
    public static ArrayList<String> fileToList(File file){
        ArrayList<String> list = new ArrayList<>();//创建一个ArrayList对象，用于存储读取的文件内容
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                list.add(s);//将读取的每一行内容添加到ArrayList中
            }
            br.close();//关闭BufferedReader对象
        }catch(Exception e){
            e.printStackTrace();//打印异常信息
        }
        return list;//返回ArrayList对象
    }
}

